extends Area2D

signal hit

@export var speed = 400 # How fast the player will move (pixels/sec).
var screen_size # Size of the game window.

var joystick_active = false      # 摇杆是否激活
var joystick_radius = 100        # 摇杆最大半径（像素）
var joystick_center = Vector2()  # 摇杆中心点（第一次触屏按下的位置）
var joystick_direction = Vector2.ZERO  # 摇杆输出的方向（标准化）

# Called when the node enters the scene tree for the first time.
func _ready():
	screen_size = get_viewport_rect().size
	hide()


func _input(event):
	if event is InputEventScreenTouch:
		if event.pressed:
			# 第一次按下时，记录摇杆中心点
			joystick_center = event.position
			joystick_active = true
		else:
			# 触屏释放时，重置摇杆
			joystick_active = false
			joystick_direction = Vector2.ZERO
	
	elif event is InputEventScreenDrag and joystick_active:
		# 计算触屏当前位置与摇杆中心的偏移量
		var touch_offset = event.position - joystick_center
		# 限制偏移量不超过摇杆半径，并标准化方向
		joystick_direction = touch_offset.normalized()


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	var velocity = Vector2.ZERO # The player's movement vector.
	if joystick_active:
		velocity = joystick_direction * speed
	else:
		if Input.is_action_pressed("ui_right"):
			velocity.x += 1
		if Input.is_action_pressed("ui_left"):
			velocity.x -= 1
		if Input.is_action_pressed("ui_down"):
			velocity.y += 1
		if Input.is_action_pressed("ui_up"):
			velocity.y -= 1

	if velocity.length() > 0:
		velocity = velocity.normalized() * speed
		$AnimatedSprite2D.play()
	else:
		$AnimatedSprite2D.stop()
	
	position += velocity * delta
	position = position.clamp(Vector2.ZERO, screen_size)
	
	if velocity.x != 0:
		$AnimatedSprite2D.animation = "walk"
		$AnimatedSprite2D.flip_v = false
		# See the note below about the following boolean assignment.
		$AnimatedSprite2D.flip_h = velocity.x < 0
	elif velocity.y != 0:
		$AnimatedSprite2D.animation = "up"
		$AnimatedSprite2D.flip_v = velocity.y > 0


func _on_body_entered(body):
	hide() # Player disappears after being hit.
	hit.emit()
	# Must be deferred as we can't change physics properties on a physics callback.
	$CollisionShape2D.set_deferred("disabled", true)

func start(pos):
	position = pos
	show()
	$CollisionShape2D.disabled = false
